//
//  FTTextField.m
//  FashionTech
//
//  Created by JackieYip on 16/5/15.
//  Copyright © 2016年 mondial-d. All rights reserved.
//

#import "FTTextField.h"
#import <objc/runtime.h>

static NSString *const FTPlaceholderColorKeyPath = @"_placeholderLabel.textColor";

@implementation FTTextField

//+ (void)initialize
//{
//    unsigned int count;
//    Ivar *ivars = class_copyIvarList(self, &count);
//    for (int i = 0; i < count; i++) {
//        Ivar ivar = *(ivars + i);
//        FTLog(@"%s", ivar_getName(ivar));
//    }
//}

- (instancetype)init
{
    if (self = [super init]) {
        [self setup];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self setup];
    }
    return self;
}

- (void)setup
{
    // set cursor color
    self.tintColor = self.textColor;
    [self resignFirstResponder];
}

- (void)awakeFromNib
{
    [super awakeFromNib];
    [self setup];
}

- (BOOL)becomeFirstResponder
{
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0) {
        [self setValue:self.textColor forKeyPath:FTPlaceholderColorKeyPath];
    }
    return [super becomeFirstResponder];
}

- (BOOL)resignFirstResponder
{
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0) {
        [self setValue:[UIColor grayColor] forKeyPath:FTPlaceholderColorKeyPath];
    }
    return [super resignFirstResponder];
}

- (CGRect)textRectForBounds:(CGRect)bounds
{
    CGRect rect = [super textRectForBounds:bounds];
    if (self.borderStyle == UITextBorderStyleNone && self.textAlignment == NSTextAlignmentLeft) {
        if (self.leftView) {
            rect.origin.x = 32.0f;
        }
        else
            rect.origin.x = 7.0f;
    }
    
    return rect;
}

- (CGRect)editingRectForBounds:(CGRect)bounds
{
    CGRect rect = [super editingRectForBounds:bounds];
    if (self.borderStyle == UITextBorderStyleNone && self.textAlignment == NSTextAlignmentLeft) {
        if (self.leftView) {
            rect.origin.x = 32.0f;
            rect.size.width -= 18.0f;
        }
        else
            rect.origin.x = 7.0f;
    }
    
    return rect;
}

@end
